package com.dream.inspect.common.utils;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.toolkit.StringUtils;
import com.dream.inspect.modules.business.entity.SendMessageEntity; 

public class JaxbObjectAndXmlUtil {

    /**
     * @param xmlStr 字符串
     * @param c 对象Class类型
     * @return 对象实例
     */
    @SuppressWarnings("unchecked")
    public static <T> T xml2Object(String xmlStr,Class<T> c)
    { 
        try
        { 
            JAXBContext context = JAXBContext.newInstance(c); 
            Unmarshaller unmarshaller = context.createUnmarshaller(); 
             
            T t = (T) unmarshaller.unmarshal(new StringReader(xmlStr)); 
             
            return t; 
             
        } catch (JAXBException e) {  e.printStackTrace();  return null; } 
         
    } 
       
    /**
     * @param object 对象
     * @return 返回xmlStr
     */
    public static String object2Xml(Object object)
    { 
        try
        {   
            StringWriter writer = new StringWriter();
            JAXBContext context = JAXBContext.newInstance(object.getClass()); 
            Marshaller  marshal = context.createMarshaller();
             
            marshal.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // 格式化输出 
            marshal.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");// 编码格式,默认为utf-8 
            marshal.setProperty(Marshaller.JAXB_FRAGMENT, false);// 是否省略xml头信息 
            marshal.setProperty("jaxb.encoding", "utf-8"); 
            marshal.marshal(object,writer);
             
            return new String(writer.getBuffer());
             
        } catch (Exception e) { e.printStackTrace(); return null;}    
         
    } 
     
    public static void main(String[] args) {
    	SendMessageEntity mb = new SendMessageEntity();
    	mb.setRequestid("请求ID");
    	mb.setYid("原数据库ID");
    	mb.setTitle("标题");
    	mb.setContent("内容");
    	mb.setTsxx("提示信息");
    	mb.setIscl("处理状态");
    	mb.setIsdx("短信发送状态");
    	mb.setSjch("手机长号");
    	mb.setJjcd("紧急程度");
    	mb.setXxtyp("消息推送类型");
    	mb.setXxval("消息推送类型对应的内容");
    	mb.setOpenurl("打开路径");
    	mb.setOtherurl("其他打开路径");
    	
    	String xmlStr = JaxbObjectAndXmlUtil.object2Xml(mb);//构造报文 XML 格式的字符串
        System.out.println("对象转xml报文： \n"+xmlStr);
         
        SendMessageEntity msgBean2 = JaxbObjectAndXmlUtil.xml2Object(xmlStr, SendMessageEntity.class);
        String type = msgBean2.getType();
        if (StringUtils.isNotEmpty(type)) {
        	
        }
        System.out.println("报文转xml转： \n"+JSON.toJSONString(msgBean2));
    	
    }
}
